import { View, Text, Image, Button } from '@tarojs/components'
import { useLoad } from '@tarojs/taro'
import { OsCheckbox, OsCheckboxOption } from 'ossaui'
import { useSelector, useDispatch } from 'react-redux'
import { useMemo } from 'react'
import './car.scss'

export default function Index() {
  const carList = useSelector(state => state.carList)
  const dispatch = useDispatch()

  useLoad(() => {
    console.log('Page loaded.')
  })

  const onSubCount = (id) => {
    dispatch({
      type: 'CHANGE_COUNT',
      payload: {
        id,
        actionType: 0
      }
    })
  }

  const onAddCount = (id) => {
    dispatch({
      type: 'CHANGE_COUNT',
      payload: {
        id,
        actionType: 1
      }
    })
  }

  const allPrice = useMemo(() => {
    return carList.filter(item => item.checked).reduce((prev, next) => {
      return prev + next.count * next.price
    }, 0)
  }, [carList])

  return (
    <View className='index'>
      {
        carList.map(item => {
          return (
            <View className='item'>
              <OsCheckbox>
                <OsCheckboxOption value={item.checked ? [true] : []} optionValue={true} onClick={(e) => {
                  dispatch({
                    type: 'CHECK_ITEM',
                    payload: {
                      id: item.id,
                      checked: !!e.length
                    }
                  })
                }} />
              </OsCheckbox>
              <Image src={item.image} className='itemImage' />
              <View className='itemDetail'>
                <Text className='itemTitle'>{item.title}</Text>
                <Text className='itemPrice'>¥ {item.price}</Text>
                <View>
                  <Button size='mini' disabled={item.count === 1} onClick={() => { onSubCount(item.id) }}>-</Button>
                  <Text>{item.count}</Text>
                  <Button size='mini' onClick={() => { onAddCount(item.id) }}>+</Button>
                </View>
              </View>
            </View>
          )
        })
      }
      <View className='footer'>
        <OsCheckbox>
          <OsCheckboxOption
            optionValue={true}
            value={carList.every(item => item.checked) ? [true] : []}
            onClick={(e) => {
              console.log(e)
              dispatch({
                type: 'CHECK_ALL',
                payload: {
                  checked: !!e.length
                }
              })
            }}
          >
            全选
          </OsCheckboxOption>
        </OsCheckbox>
        <Text>总价： ¥{allPrice}</Text>
        <Button>提交</Button>
      </View>
    </View>
  )
}
